/**
    @user: lcz
    @date: 2020/9/9
    @op: 上传文件服务
**/
package services

import (
	"errors"
	"fmt"
	"github.com/spf13/viper"
	"io"
	"math/rand"
	"mime/multipart"
	"os"
	"strings"
	"time"
)

type UploadService struct {
	Dir string	// 目录
	Path string  // 存储路径
	FileName string  // 文件名称
	Ext	 []string   // 允许文件后缀
	Size int64 // 允许文件大小
}

// 配置初始化
func (u *UploadService) Init()  {
	dir := viper.GetString("app.upload.local.dir")
	size := viper.GetInt64("app.upload.local.size")
	ext := viper.GetStringSlice("app.upload.local.ext")
	u.Size = size
	u.Dir = dir
	u.Ext = ext
}

// 上传
func (u *UploadService) Upload(file *multipart.FileHeader) (string, error) {
	size := file.Size
	header := file.Header
	extArr := strings.Split(header["Content-Type"][0], "/")
	ext := extArr[1]
	// 检测目录
	err := u.checkDir()
	// 检测文件大小
	err = u.checkSize(size)
	// 检测文件后缀
	err = u.checkExt(ext)
	// 生成文件名
	fileName := u.createFileName("", ext)
	// 创建新文件
	filePath := fmt.Sprintf("%s/%s", u.Dir, fileName)
	dstfile, err := os.Create(filePath)
	if err != nil {
		return "",err
	}
	srcFile,_ := file.Open()
	// 把源文件拷贝到新文件
	_,err = io.Copy(dstfile, srcFile)
	if err != nil {
		return "",err
	}

	return filePath,nil
}

func (u *UploadService) createFileName(name string, ext string) string {
	if name == "" {
		newName := fmt.Sprintf("%d_%d.%s",time.Now().Unix(), rand.Intn(9999), ext)
		return newName
	}

	return name
}

func (u *UploadService) checkExt(ext string)  error {
	for _,v := range u.Ext {
		if ext == v {
			return nil
		}
	}

	return errors.New("不支持文件后缀")
}

func (u *UploadService) checkDir() error {
	_, err := os.Stat(u.Dir)
	if err != nil {
		b := os.IsExist(err)
		if b != true {
			return errors.New("目录不存在")
		}
	}
	return nil
}

func (u *UploadService) checkSize(size int64) error {
	if size > u.Size {
		return errors.New("文件大小超过最大上传限制")
	}

	return nil
}
